package com.zsw.receiver;

import com.zsw.entity.RepertoryEntity;
import com.zsw.service.ProductService;
import com.zsw.service.RepertoryService;
import com.zsw.util.RedisUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component
@RabbitListener(queues = "ticketProvider")
public class TicketReceiver {
    @Autowired
    ProductService productService;
    @Autowired
    RepertoryService repertoryService;
    @Autowired
    RedisUtils redisUtils;

//    @Resource
//    private RedissonClient client;
    private static volatile Lock lock=new ReentrantLock();
    @RabbitHandler
//    @Transactional(rollbackFor = Exception.class)
    public void process(Map mapMsg) throws Exception {
        lock.lock();
            System.out.println(mapMsg.toString());
            int productId = (Integer) mapMsg.get("productId");
            String userName = mapMsg.get("user").toString();
            try {
                    String value = redisUtils.get("ticket" + productId);
                    if (!value.isEmpty()) {
                        int count = Integer.valueOf(value);
                        if (count >= 1) {
                            count--;
                            if (count != 0) {
                                redisUtils.set("ticket" + productId, String.valueOf(count), 1200);
                                redisUtils.set("order" + productId + ":" + count, userName, 1200);
                                System.out.println(userName + "抢到票，还有" + count + "票");
                            } else {
                                redisUtils.set("ticketStatus", String.valueOf(-1), 1200);
                                RepertoryEntity entity = repertoryService.getById(productId);
                                entity.setProductCount(count);
                                repertoryService.updateById(entity);
                                System.out.println("订单写入数据库中！请稍后");
                            }
                        } else {
                            System.out.println("库存为空");
                        }
                    } else {
                        System.out.println("库存为空");
                    }

            } catch (Exception ex) {
                System.out.println("抢票异常+" + ex.getMessage());
//                throw new Exception("a");
            }
            finally {
                lock.unlock();
            }
    }

}
